package net.wang.concurrency.test.aqs;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class CountDownLatchExample1 {

    public static final int threadCount = 200;

    @Test
    public void testCountDownLatch() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int threadNumber = i;
            executorService.execute(() -> {
                try {
                    out(threadNumber);
                } catch (InterruptedException e) {
                    log.error("exception : {}", e.getMessage());
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await(); //保证线程池里的线程都执行完成
        log.info("===== finish ======");
        executorService.shutdown(); //关闭线程池
    }

    private void out(int threadNumber) throws InterruptedException {
        Thread.sleep(100);
        log.info("num = {}", threadNumber);
        Thread.sleep(100);
    }
}
